import { defineStore } from "pinia"
import { DocPkgMaterialPageSearch, DocPkgMaterialPageResult} from "@/models/material"
import { materialApi } from "@/services"

const useDocpkgStore  = defineStore('Docpkg', {
    // state
    state:() =>({
        docPkgId: 0,

        pageSize: 10,
        pageNum: 1,
        totalRecords: 0,
        docpkgMaterialPageResult: {} as DocPkgMaterialPageResult,
    }),

    // actions
    actions:{
        // 获得指定资料包资料列表
        async getDocPkgMaterials(docPkgId: number, pageSize:number, pageNum:number) {
            try {
                const data = {
                    docPkgId: docPkgId,
                    pageSize: pageSize,
                    pageNum: pageNum,
                } as DocPkgMaterialPageSearch;
                const res = await materialApi.getDocPkgMaterials(data)
                this.docpkgMaterialPageResult = res
                this.totalRecords = this.docpkgMaterialPageResult.count
            } catch(err) {
        
            }
        },

        // 加为我的资料
        async addAsMyMaterial(id:number) {
            try {
                const res = await materialApi.addAsMyMaterial(id)
                return res? res.result : false
            } catch(err) {
                return false
            }
        },

        // 初始化数据
        async initData(docPkgId: number){
            this.docPkgId = docPkgId;
            await this.refreshData();
        },

        // 刷新数据（在当前页）
        async refreshData(){
            await this.getDocPkgMaterials(this.docPkgId,this.pageSize,this.pageNum)
        },

        // 开始查询
        async handleSearch(){      
            await this.getDocPkgMaterials(this.docPkgId,this.pageSize,1)
        },

        async handlePageChange(pageNum:number,pageSize:number){     
            this.pageNum = pageNum
            this.pageSize = pageSize   
            this.refreshData()
        }
    },
    getters:{
        docpkgMaterialSource:(state) => state.docpkgMaterialPageResult.records,
    }
})

export default useDocpkgStore;